package com.qianbei.view.transport;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.qianbei.R;
import com.qianbei.bean.ChangeCarBean;
import com.qianbei.bean.ChangeOrderBean;
import com.qianbei.bean.ChangeStationBean;
import com.qianbei.bean.GetTransport2;
import com.qianbei.bean.RequeastBean1;
import com.qianbei.common.base.BaseActivity;
import com.qianbei.common.base.Basebean;
import com.qianbei.common.base.MyApplication;
import com.qianbei.common.init.SetData;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.okhttp.RequeastBean;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.common.net.view.ProgressDialog;
import com.qianbei.common.util.DeviceUtil;
import com.qianbei.view.adapter.GetCarBean;
import com.qianbei.view.bluetooth.BluetoothService;
import com.qianbei.view.errotip.ErroTipActivity;
import com.qianbei.view.orm.DaoSession;
import com.qianbei.view.orm.RequestPersistent;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class TransportfActivity extends BaseActivity {
    private static final String TAG = TransportfActivity.class.getSimpleName();
    private ListView mIncomeListView;
    @Bind(R.id.transport_finish)
    TextView transport_finish;
    @Bind(R.id.transport_shigu)
    TextView transport_shigu;
    public static final String DUAN_BO = "医-RB"; //短驳的线路名称带此字段  固定驳运
    public static final String DUAN_BO1 = "医-LB"; //短驳的线路名称带此字段  临时驳运
    public static final String DUAN_BO2 = "医-LRB"; //短驳的线路名称带此字段  周六驳运
    public static final String DUAN_BO3 = "医-RRB"; //短驳的线路名称带此字段  周日驳运
    private PointAdapter incomeAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gufei_transprot_activity);
        ButterKnife.bind(this);
        mIncomeListView = (ListView) findViewById(R.id.income_list_view);
        transport_finish.setOnClickListener(this);
        transport_shigu.setOnClickListener(this);
        setTitle("收运");
        String routeNo = SetData.getRouteNo();
      /*  现在新增短驳把这里去掉就行了
      if (!TextUtils.isEmpty(routeNo) && (routeNo.contains(DUAN_BO) || routeNo.contains(DUAN_BO1) ||
        routeNo.contains(DUAN_BO2) || routeNo.contains(DUAN_BO3))) {
            mTitle.setrightTitle("换车");
        }*/
        mTitle.setRightImage(R.drawable.disconnect_bluetooth);
        checkVehicle();
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.transport_finish:
                show();
                break;
            case R.id.transport_shigu:
                startActivity(ErroTipActivity.class);
                break;
            case R.id.tv_right:
//                startActivity(ErroTipActivity.class);
                break;
        }
    }
    @SuppressLint("StaticFieldLeak")
    @Override
    public void fClick(int id) {
        super.fClick(id);
        switch (id) {
            case R.id.tv_right:

//                startActivity(ChangeCarActivity.class);
                break;

            case R.id.title_right:
                if (BluetoothService.getInstance().getBluetoothGatt()==null){
                    Toast.makeText(TransportfActivity.this,"蓝牙尚未连接",Toast.LENGTH_SHORT).show();
                    return;
                }
                BluetoothService.getInstance().disconnectBlueTooth();
                BluetoothService.getInstance().setOnConnectStatus(new BluetoothService.OnConnectStatusListener() {
                    @Override
                    public void onDisConnSuccess() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(TransportfActivity.this,"蓝牙连接已断开",Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                });
                break;
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        checkVehicle();
    }

    /**
     * 提示用户 是否完成线路
     */
    public void show() {
        boolean isFinishAll = checkFinishAll();
        if (!isFinishAll) {
            new MsgAlert().show("有未完成收运客户，不能完路线！");
            return;
        }
        AlertDialog dialog = new AlertDialog.Builder(this)
//                .setTitle("是否绑定此车")//设置对话框的标题
                .setMessage("是否完成线路？")//设置对话框的内容
                //设置对话框的按钮
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finishCollect();
                    }
                }).create();
        dialog.show();
    }

    private boolean checkFinishAll() {
        boolean isFinish = false;
        int finishCount = 0;
        int needCount = -1;
        String jsonString = SetData.getJobs();
        JSONArray jobsAry = JSON.parseArray(jsonString);
        String jobId = SetData.getJobid();
        if (jobsAry != null) {
            for (int i = 0; i < jobsAry.size(); i++) {
                JSONObject oneJob = jobsAry.getJSONObject(i);
                String dataJobId = oneJob.getString("_id");
                if (dataJobId.equals(jobId)) {
                    JSONArray cusAry = oneJob.getJSONArray("customerAry");
                    needCount = cusAry.size();
                    for (int j = 0; j < cusAry.size(); j++) {
                        JSONObject oneCus = cusAry.getJSONObject(j);
                        String status = oneCus.getString("status");
                        if (status != null && status.equals("2")) {
                            finishCount++;
                        }
                    }
                }
            }
        }
        if (needCount == finishCount) {
            isFinish = true;
        }

        return isFinish;
    }

    /**
     * 获取收运信息 展示 listview
     */
    private void checkVehicle() {
        //取车时缓存了 JOB 的 json string  根据用户点选的派车单进行收运
        String jsonString = SetData.getJobs();
        if (TextUtils.isEmpty(jsonString)) {
            return;
        }
        JSONArray jobsAry = JSON.parseArray(jsonString);
        String jobId = SetData.getJobid();

        Log.d("Transport BusinessType", SetData.getBusinessType() + " ");

        for (int i = 0; i < jobsAry.size(); i++) {
            JSONObject oneJob = jobsAry.getJSONObject(i);
            String dataJobId = oneJob.getString("_id");
            if (dataJobId.equals(jobId)) {

                JSONObject tmpData = new JSONObject();
                tmpData.put("code", 0);
                tmpData.put("message", "success");
                tmpData.put("total", 1);

                JSONArray array = new JSONArray();
                array.add(oneJob);

                tmpData.put("array", array);
                TrasportBean bean = JSON.parseObject(tmpData.toJSONString(), TrasportBean.class);
                SharedPreferences pref = getSharedPreferences("isOver", 0);
                SharedPreferences.Editor editor = pref.edit();
                int num = bean.getArray().get(0).getCustomerAry().size();
                for (int j = 0; j < num; j++) {
                    String id = "id" + bean.getArray().get(0).getCustomerAry().get(j).getId();
                    Boolean flag = pref.getBoolean(id, false);
                    if (!flag) {
                        editor.putBoolean(id, false).commit();
                    }
                }


                Log.d("gaoaa", " bean.getArray().size();" + bean.getArray().get(0).getCustomerAry().get(0).getId());
                incomeAdapter = new PointAdapter(TransportfActivity.this,
                        bean.getArray().get(0).getCustomerAry());
                mIncomeListView.setAdapter(incomeAdapter);
                break;
            }
        }

        //原网络方式获取派车单方式不使用， 改为用取车接口缓存的数据
        /*ServerControl sc = new ServerControl(
                new RequeastBean("select","com.cygps.dubbo.WasteTransport.ICustomersplit",
                        new GetTransport(SetData.getJobid())));
        sc.serverListener = new ServerControl.ServerListener() {

            @Override
            public void serverFinish(ServerResult sr) {
                if (sr.isContinue) {
                    TrasportBean bean  = JSON.parseObject( sr.bodyData.toString(),TrasportBean.class);

                    Log.d("gaoaa"," bean.getArray().size();"+ bean.getArray().size());
                    PointAdapter incomeAdapter = new PointAdapter(TransportfActivity.this,
                            bean.getArray().get(0).getCustomerAry());
                    mIncomeListView.setAdapter(incomeAdapter);
                }

            }
        };
        new ProgressDialog(mContext).OKpost(sc);*/
    }

    /**
     * 完成线路 的请求
     */
    private void finishCollect() {
        ServerControl sc = new ServerControl(
                new RequeastBean("finishCollect", "com.cygps.dubbo.WasteTransport.IPdaBoxManagement",
                        new GetTransport2()));
        sc.serverListener = new ServerControl.ServerListener() {

            @Override
            public void serverFinish(ServerResult sr) {
                if (sr.isContinue) {
                    new MsgAlert().show("已经完成路线");
                    showTip();
                }
            }
        };
        new ProgressDialog(mContext).OKpost(sc);
    }

    /**
     * 提示是否生成二车工单
     */
    private void showTip() {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("提示")//设置对话框的标题
                .setMessage("是否生成短驳二车工单？")//设置对话框的内容
                //设置对话框的按钮
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        RequeastBean bean =
                                new RequeastBean1("select", "com.cygps.dubbo.commons.data.ICommonDataService",
                                        new Basebean(),"WT_TransferStation");
                        ServerControl sc = new ServerControl(bean);
                        sc.serverListener = new ServerControl.ServerListener() {
                            @Override
                            public void serverFinish(ServerResult sr) {
                                if (sr.isContinue) {
                                    try {
                                        org.json.JSONArray js = sr.bodyData.optJSONArray("array");
                                        List<ChangeStationBean> stationBeans = JSON.parseArray(js.toString(), ChangeStationBean.class);
                                        showOrderTip(stationBeans);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        };
                        new ProgressDialog(mContext).OKpost1(sc,"正在加载中转站...");
                    }
                }).create();
        if (!isFinishing()) {
            dialog.show();
        }
    }

    /**
     * 生成短驳工单选择对应路线
     * @param stationBeans
     */
    private void showOrderTip(final List<ChangeStationBean> stationBeans) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final String[] texts = new String[stationBeans.size()];
        final boolean[] bs = new boolean[stationBeans.size()];
        for (int i = 0; i < stationBeans.size(); i++) {
            ChangeStationBean stationBean = stationBeans.get(i);
            texts[i] = stationBean.getName();
        }
        builder.setTitle("选择中转站")
                .setMultiChoiceItems(texts, bs, new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                        bs[which] = isChecked;
                    }
                });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                List<String> ids = new ArrayList<>();
                for (int i = 0; i < stationBeans.size(); i++) {
                    if (bs[i]) {
                        ids.add(stationBeans.get(i).get_id());
                    }
                }
                String[] arr = ids.toArray(new String[ids.size()]);
                saveChangeOrder(arr);
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    private void saveChangeOrder(String[] ids) {
        String jobId = SetData.getJobid();
        if (TextUtils.isEmpty(jobId)) {
            new MsgAlert().show("请退出重新绑定车辆");
            return;
        }
        RequeastBean bean =
                new RequeastBean("addRoute", "com.cygps.dubbo.WasteTransport.IPdaBoxnullAndLoadandunloadScan",
                        new ChangeOrderBean(jobId,ids));
        if (!DeviceUtil.isNetworkAvailable()) {
            DaoSession daoSession = ((MyApplication) getApplication()).getDaoSession();
            RequestPersistent requestPersistent = new RequestPersistent();
            requestPersistent.setServiceName(bean.serviceName);
            requestPersistent.setServiceMethod(bean.serviceMethod);
            requestPersistent.setServiceBody(new Gson().toJson(bean.serviceBody));
            requestPersistent.setMethodClass(ChangeCarBean.class.getName());
            daoSession.getRequestPersistentDao().insertOrReplace(requestPersistent);
            new MsgAlert().show("生成二车工单成功,退出重登即可看到二车工单");
            finish();
        } else {
            ServerControl sc = new ServerControl(bean);
            sc.serverListener = new ServerControl.ServerListener() {
                @Override
                public void serverFinish(ServerResult sr) {
                    if (sr.isContinue) {
                        new MsgAlert().show("生成二车工单成功,退出重登即可看到二车工单");
                        finish();
                    }
                }
            };
            new ProgressDialog(mContext).OKpost(sc);
        }
    }
}
